#!/bin/sh

. /opt/x1plus/libexec/functions.sh

case "$1" in
	start)

		echo "setup network params ... "

		echo 1048576 > /proc/sys/net/core/wmem_max
		echo 1048576 > /proc/sys/net/core/rmem_max
		echo "4096 1048576 1048576" > /proc/sys/net/ipv4/tcp_rmem
		echo "4096 1048576 1048576" > /proc/sys/net/ipv4/tcp_wmem
		echo 4193104 > /proc/sys/net/ipv4/tcp_limit_output_bytes
		echo 1048576 > /proc/sys/net/ipv4/udp_rmem_min
		echo 1048576 > /proc/sys/net/ipv4/udp_wmem_min
		echo "10240 87380 12582912" > /proc/sys/net/ipv4/tcp_rmem
		echo 12582912 > /proc/sys/net/core/wmem_max
		echo disabled > /sys/devices/virtual/thermal/thermal_zone0/mode
		echo performance > /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor

		if [ ! -d "/userdata/" ];then
			echo "userdata is not mounted!!!"
			exit 1
		fi

		mkdir -p /userdata/cfg
		mkdir -p /userdata/bin
		mkdir -p /config/wifi

		if [ ! -f "/config/wifi/config.txt" ];then
			echo "ccode=DE" > /config/wifi/config.txt
			echo "regrev=7" >> /config/wifi/config.txt
			echo "PM=0" >> /config/wifi/config.txt
			sync
		fi

		if [ -z $(grep 'PM=0' "/config/wifi/config.txt") ]; then
			echo "PM=0" >> /config/wifi/config.txt
			sync
		fi

		if [ ! -f "/userdata/cfg/wpa_supplicant.conf" ];then
			echo "wpa_supplicant.conf init"
			cp /etc/wpa_supplicant.conf /userdata/cfg/
			sync
		fi

		if [ ! -f "/userdata/bin/dnsmasq.conf" ];then
			echo "wpa_supplicant.conf init"
			cp /etc/dnsmasq.conf /userdata/bin/
			sync
		fi

		cp /system/etc/firmware/nvram_ap6212a_ce.txt /config/wifi/nvram_ap6212a.txt
		grep -v ccode /config/wifi/nvram_ap6212a.txt > /var/run/brcmfmac43430-sdio.txt
		cat /config/wifi/config.txt >> /var/run/brcmfmac43430-sdio.txt

		cp /system/etc/firmware/nvram_ap6256.txt /config/wifi/nvram_ap6256.txt
		grep -v ccode /config/wifi/nvram_ap6256.txt > /var/run/brcmfmac43456-sdio.txt
		cat /config/wifi/config.txt >> /var/run/brcmfmac43456-sdio.txt

		echo 1 > /sys/class/rfkill/rfkill1/state

		if x1p_get_setting boot.wifi_driver.bcmdhd; then
			for i in cfg80211 mac80211 rk_wifi_config bcmdhd; do
				printf "load wifi module $i: "
				insmod /system/lib/modules/bcmdhd/$i.ko
				[ $? = 0 ] && echo "OK" || echo "FAIL"
			done
		else
			for i in compat cfg80211 brcmutil brcmfmac; do
				printf "load wifi module $i: "
				insmod /system/lib/modules/brcmfmac/$i.ko
				[ $? = 0 ] && echo "OK" || echo "FAIL"
			done
		fi

		;;
	stop)

		echo 0 > /sys/class/rfkill/rfkill0/state

		;;
	restart|reload)
		$0 stop
		$0 start
		;;
	*)
		echo "Usage: $0 {start|stop|restart}"
		exit 1
esac

exit 0
